<template>
  <div class="system-log-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">
            <el-icon><Document /></el-icon>
            操作日志
          </span>
          <el-button 
            v-permission="'log.export'" 
            type="success" 
            :icon="Download" 
            @click="handleExport"
          >
            导出日志
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchForm.search"
          placeholder="搜索用户名、操作内容"
          style="width: 250px"
          clearable
          @clear="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-select
          v-model="searchForm.log_type"
          placeholder="操作类型"
          clearable
          style="width: 150px; margin-left: 10px"
          @change="handleSearch"
        >
          <el-option 
            v-for="type in logTypes" 
            :key="type.value" 
            :label="type.label" 
            :value="type.value" 
          />
        </el-select>

        <el-input
          v-model="searchForm.module"
          placeholder="操作模块"
          clearable
          style="width: 150px; margin-left: 10px"
          @clear="handleSearch"
        />

        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 240px; margin-left: 10px"
          @change="handleDateChange"
        />

        <el-button type="primary" :icon="Search" @click="handleSearch" style="margin-left: 10px">
          搜索
        </el-button>
        <el-button :icon="RefreshRight" @click="handleReset">重置</el-button>
      </div>

      <!-- 统计信息 -->
      <el-row :gutter="20" style="margin-top: 20px">
        <el-col :span="6">
          <el-statistic title="总日志数" :value="stats.total">
            <template #prefix>
              <el-icon><Document /></el-icon>
            </template>
          </el-statistic>
        </el-col>
        <el-col :span="6">
          <el-statistic title="今日操作" :value="stats.today">
            <template #prefix>
              <el-icon><Calendar /></el-icon>
            </template>
          </el-statistic>
        </el-col>
        <el-col :span="6">
          <el-statistic title="成功操作" :value="successCount" :precision="0">
            <template #prefix>
              <el-icon style="color: #67C23A"><SuccessFilled /></el-icon>
            </template>
          </el-statistic>
        </el-col>
        <el-col :span="6">
          <el-statistic title="失败操作" :value="failCount" :precision="0">
            <template #prefix>
              <el-icon style="color: #F56C6C"><CircleCloseFilled /></el-icon>
            </template>
          </el-statistic>
        </el-col>
      </el-row>

      <!-- 日志列表 -->
      <el-table 
        :data="logList" 
        v-loading="loading"
        border
        stripe
        style="margin-top: 20px"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="操作用户" width="120" />
        <el-table-column label="操作类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getLogTypeTag(row.log_type)">
              {{ getLogTypeLabel(row.log_type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="module" label="操作模块" width="120" />
        <el-table-column prop="action" label="操作内容" min-width="250" />
        <el-table-column prop="ip_address" label="IP地址" width="140" />
        <el-table-column label="操作结果" width="100">
          <template #default="{ row }">
            <el-tag :type="row.result ? 'success' : 'danger'">
              {{ row.result ? '成功' : '失败' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleViewDetail(row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 20px; justify-content: flex-end"
        @size-change="handleSearch"
        @current-change="handleSearch"
      />
    </el-card>

    <!-- 日志详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="日志详情"
      width="700px"
    >
      <el-descriptions v-if="currentLog" :column="2" border>
        <el-descriptions-item label="日志ID">{{ currentLog.id }}</el-descriptions-item>
        <el-descriptions-item label="操作用户">{{ currentLog.username }}</el-descriptions-item>
        <el-descriptions-item label="操作类型">
          <el-tag :type="getLogTypeTag(currentLog.log_type)">
            {{ getLogTypeLabel(currentLog.log_type) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="操作模块">{{ currentLog.module }}</el-descriptions-item>
        <el-descriptions-item label="IP地址" :span="2">
          {{ currentLog.ip_address }}
        </el-descriptions-item>
        <el-descriptions-item label="操作内容" :span="2">
          {{ currentLog.action }}
        </el-descriptions-item>
        <el-descriptions-item label="操作结果" :span="2">
          <el-tag :type="currentLog.result ? 'success' : 'danger'">
            {{ currentLog.result ? '成功' : '失败' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="错误信息" :span="2" v-if="!currentLog.result">
          <div style="color: #f56c6c">{{ currentLog.error_message || '-' }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="User Agent" :span="2">
          <div style="word-break: break-all; font-size: 12px">
            {{ currentLog.user_agent || '-' }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="操作时间" :span="2">
          {{ formatDate(currentLog.created_at) }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Document, Download, Search, RefreshRight, Calendar,
  SuccessFilled, CircleCloseFilled
} from '@element-plus/icons-vue'
import { getLogList, getLogTypes, getLogStats } from '@/api/system'

// 日志类型
const logTypes = ref([])

// 搜索表单
const searchForm = reactive({
  search: '',
  log_type: '',
  module: '',
  start_date: '',
  end_date: ''
})

// 日期范围
const dateRange = ref([])

// 日志列表
const logList = ref([])
const loading = ref(false)

// 统计信息
const stats = ref({
  total: 0,
  today: 0,
  by_type: {}
})

// 计算成功和失败数量
const successCount = computed(() => {
  return logList.value.filter(log => log.result).length
})

const failCount = computed(() => {
  return logList.value.filter(log => !log.result).length
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 详情对话框
const detailDialogVisible = ref(false)
const currentLog = ref(null)

// 获取日志类型标签颜色
const getLogTypeTag = (type) => {
  const tagMap = {
    'create': 'success',
    'update': 'warning',
    'delete': 'danger',
    'login': 'primary',
    'logout': 'info',
    'export': 'success',
    'import': 'success',
    'other': ''
  }
  return tagMap[type] || ''
}

// 获取日志类型标签
const getLogTypeLabel = (type) => {
  const typeObj = logTypes.value.find(t => t.value === type)
  return typeObj ? typeObj.label : type
}

// 处理日期变化
const handleDateChange = (dates) => {
  if (dates && dates.length === 2) {
    searchForm.start_date = dates[0].toISOString().split('T')[0]
    searchForm.end_date = dates[1].toISOString().split('T')[0]
  } else {
    searchForm.start_date = ''
    searchForm.end_date = ''
  }
  handleSearch()
}

// 获取日志类型列表
const fetchLogTypes = async () => {
  try {
    const response = await getLogTypes()
    logTypes.value = response
  } catch (error) {
    console.error('获取日志类型失败:', error)
    // 使用默认类型
    logTypes.value = [
      { value: 'create', label: '创建' },
      { value: 'update', label: '更新' },
      { value: 'delete', label: '删除' },
      { value: 'login', label: '登录' },
      { value: 'logout', label: '登出' },
      { value: 'export', label: '导出' },
      { value: 'import', label: '导入' },
      { value: 'other', label: '其他' }
    ]
  }
}

// 获取统计信息
const fetchStats = async () => {
  try {
    const response = await getLogStats()
    stats.value = response
  } catch (error) {
    console.error('获取统计信息失败:', error)
  }
}

// 获取日志列表
const fetchLogList = async () => {
  loading.value = true
  try {
    // 过滤掉空参数
    const params = {
      page: pagination.page,
      page_size: pagination.pageSize
    }
    
    // 只添加非空的搜索参数
    if (searchForm.search) params.search = searchForm.search
    if (searchForm.log_type) params.log_type = searchForm.log_type
    if (searchForm.module) params.module = searchForm.module
    if (searchForm.result !== '') params.result = searchForm.result
    if (searchForm.date_range && searchForm.date_range.length === 2) {
      params.start_date = searchForm.date_range[0]
      params.end_date = searchForm.date_range[1]
    }
    
    const response = await getLogList(params)
    logList.value = response.results || response
    pagination.total = response.count || 0
  } catch (error) {
    ElMessage.error('获取日志列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchLogList()
}

// 重置
const handleReset = () => {
  searchForm.search = ''
  searchForm.log_type = ''
  searchForm.module = ''
  searchForm.start_date = ''
  searchForm.end_date = ''
  dateRange.value = []
  handleSearch()
}

// 查看详情
const handleViewDetail = (row) => {
  currentLog.value = row
  detailDialogVisible.value = true
}

// 导出日志
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

// 挂载时获取数据
onMounted(() => {
  fetchLogTypes()
  fetchStats()
  fetchLogList()
})
</script>

<style scoped>
.system-log-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header .title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
}

.search-bar {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px 0;
}
</style>

